import React, { Component } from 'react';
import { Card, Button, Modal, Form, Input, message, Select, Tree, Transfer } from 'antd';
import ETable from '../../components/ETable';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { formateDate, updateSelectedItem } from '../../util';
import menuConfig from '../../configs/left_menu_configs';

const { Item } = Form;
const { Option } = Select;
const { TreeNode } = Tree;

const formItemLayout = {
  labelCol: {
    xs: 24,
    sm: 4
  },
  wrapperCol: {
    xs: 24,
    sm: 15
  }
};

class PermissionUser extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: '',
      isRoleVisible: false,    // 显示创建角色的弹框
      isPermVisible: false,    // 显示设置权限的弹框
      isUserVisible: false,    // 显示用户授权的弹框
      detailInfo: {},   // 选中的条目详情
      menuInfo: [],     // 菜单条目
    };
    this.updateSelectedItem = updateSelectedItem.bind(this);
  }

  render() {
    const columns = [
      {
        title: '角色ID',
        dataIndex: 'id'
      },
      {
        title: '角色名称',
        dataIndex: 'role_name'
      },
      {
        title: '创建时间',
        dataIndex: 'create_time'
      },
      {
        title: '使用状态',
        dataIndex: 'status',
        render(status) {
          return status === 1 ? '启用' : '停用'
        }
      },
      {
        title: '授权时间',
        dataIndex: 'authorize_time',
        render: formateDate
      },
      {
        title: '授权人',
        dataIndex: 'authorize_user_name'
      }
    ];
    const { permissionList, mockData, targetKeys } = this.props;
    const { isRoleVisible, isPermVisible, isUserVisible, detailInfo, menuInfo } = this.state;
    return (
      <div>
        <Card title="权限管理" className="pinlor-cards pinlor-buttons">
          <Button type="primary" onClick={this.handleRoleShow}>创建角色</Button>
          <Button type="primary" onClick={this.handlePermission}>设置权限</Button>
          <Button type="primary" onClick={this.handleUserAuth}>用户授权</Button>
        </Card>
        <div className="content-wrap">
          <ETable
            updateSelectedItem={this.updateSelectedItem}
            selectedRowKeys={this.state.selectedRowKeys}
            dataSource={permissionList}
            columns={columns} />
        </div>
        <Modal
          title="创建角色"
          visible={isRoleVisible}
          onOk={this.handleRoleSubmit}
          onCancel={this.handleModalCancel}
        >
          <RoleForm wrappedComponentRef={ins => this.roleForm = ins} />
        </Modal>
        <Modal
          title="设置权限"
          visible={isPermVisible}
          width={600}
          onOk={this.handlePermEditSubmit}
          onCancel={this.handlePermEditCancel}
        >
          <PermEditForm
            detailInfo={detailInfo}
            menuInfo={menuInfo}
            wrappedComponentRef={ins => this.permForm = ins}
            patchMenuInfo={this.handlePatchMenu} />
        </Modal>
        <Modal
          title="用户授权"
          visible={isUserVisible}
          width={800}
          onOk={this.handleUserSubmit}
          onCancel={this.handleUserCancel}
        >
          <RoleAuthForm
            detailInfo={detailInfo}
            targetKeys={targetKeys}
            mockData={mockData}
            wrappedComponentRef={ins => this.userAuthForm = ins}
            patchUserInfo={targetKeys=>{
              this.props.setTargetKeys(targetKeys);
            }}
          />
        </Modal>
      </div>
    )
  }

  componentDidMount() {
    this.props.getPermissionList();
  }

  handleRoleShow = () => {
    // 打开创建角色的弹框
    this.setState({
      isRoleVisible: true
    })
  };

  handleModalCancel = () => {
    // 关闭创建角色的弹框
    this.roleForm.props.form.resetFields();
    this.setState({
      isRoleVisible: false
    })
  };
  handleRoleSubmit = () => {
    // 创建角色提交
    let data = this.roleForm.props.form.getFieldsValue();
    console.log(JSON.stringify(data));
    message.info('角色已创建成功');
    this.handleModalCancel();
  };

  handlePermission = () => {
    // 打开权限设置
    let item = this.state.selectedItem;
    if (!item) {
      Modal.warning({
        title: '提示',
        content: '请选择一个角色'
      });
      return;
    }
    this.setState({
      isPermVisible: true,
      detailInfo: item,
      menuInfo: item.menus
    })
  };
  handlePermEditCancel = () => {
    // 关闭权限设置
    this.setState({
      isPermVisible: false
    })
  };
  handlePermEditSubmit = () => {
    // 提交权限设置
    let data = this.permForm.props.form.getFieldsValue();
    data['role_id'] = this.state.selectedItem.id;
    data.menus = this.state.menuInfo;
    console.log(JSON.stringify(data, null, 2));
    this.handlePermEditCancel()
  };

  handlePatchMenu = checkedKeys => {
    // 更改权限菜单
    this.setState({
      menuInfo: checkedKeys
    })
  }

  handleUserAuth = () => {
    /*打开用户授权弹框*/
    const item = this.state.selectedItem;
    if (!item) {
      Modal.warning({
        title: '提示',
        content: '请选择一个角色'
      });
      return;
    }
    this.props.getUserList();
    this.setState({
      detailInfo: item,
      isUserVisible: true
    })
  };

  handleUserSubmit = () => {
    let data = {};
    data.user_ids = this.props.targetKeys;
    data.role_id = this.state.selectedItem.id;
    console.log(JSON.stringify(data));
    message.success('用户授权成功');
    this.handleUserCancel();
  };
  handleUserCancel = () => {
    this.setState({
      isUserVisible: false
    })
  };
}

const mapStateToProps = state => {
  const { permissionList, userList, mockData, targetKeys } = state.permission;
  return {
    permissionList,
    userList,
    mockData,
    targetKeys
  }
};

const mapDispatchToProps = dispatch => ({
  getPermissionList() {
    dispatch(actionCreators.getPermissionListData());
  },
  getUserList() {
    dispatch(actionCreators.getUserListData());
  },
  setTargetKeys(targetKeys){
    dispatch(actionCreators.setTargetKeys(targetKeys));
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(PermissionUser);


class RoleForm extends Component {
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form>
        <Item label="角色名称" {...formItemLayout}>
          {
            getFieldDecorator('role_name')(<Input placeholder="请输入角色名称" />)
          }
        </Item>
        <Item label="角色状态" {...formItemLayout}>
          {
            getFieldDecorator('state')(
              <Select>
                <Option value="1">开启</Option>
                <Option value="0">关闭</Option>
              </Select>
            )
          }
        </Item>
      </Form>
    );
  }
}

RoleForm = Form.create()(RoleForm);

class PermEditForm extends Component {
  render() {
    const { detailInfo, form, menuInfo } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form>
        <Item label="角色名称" {...formItemLayout}>
          <Input disabled placeholder={detailInfo['role_name']} />
        </Item>
        <Item label="角色状态" {...formItemLayout}>
          {
            getFieldDecorator('state', {
              initialValue: detailInfo.status
            })(
              <Select>
                <Option value={1}>开启</Option>
                <Option value={0}>关闭</Option>
              </Select>
            )
          }
        </Item>
        <Tree
          checkable
          defaultExpandAll
          onCheck={checkedKeys => {
            this.onCheck(checkedKeys);
          }}
          checkedKeys={menuInfo}
        >
          <TreeNode title="平台权限" key="platform_all">
            {
              this.renderTreeNodes(menuConfig)
            }
          </TreeNode>
        </Tree>
      </Form>
    );
  }

  renderTreeNodes = data => {
    // 生成菜单的树状结构
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode {...item}>
            {
              this.renderTreeNodes(item.children)
            }
          </TreeNode>
        )
      }
      return <TreeNode {...item} />
    })
  };

  onCheck = checkedKeys => {
    this.props.patchMenuInfo(checkedKeys);
  }
}

PermEditForm = Form.create()(PermEditForm);

class RoleAuthForm extends Component {
  render() {
    const { detailInfo, mockData, targetKeys } = this.props;
    return (
      <Form>
        <Item label="角色名称" {...formItemLayout}>
          <Input disabled placeholder={detailInfo['role_name']} />
        </Item>
        <Item label="选择用户" {...formItemLayout}>
          <Transfer
            listStyle={{width: 200, height:400}}
            dataSource={mockData}
            targetKeys={targetKeys}
            titles={['待选用户', '已选用户']}
            showSearch
            searchPlaceholder="请输入用户名"
            filterOption={this.filterOption}
            render={item => item.title}
            onChange={this.handleChange}
          />
        </Item>
      </Form>
    );
  }

  filterOption = (inputValue, option) => {
    return option.title.indexOf(inputValue) > -1;
  };

  handleChange = targetKeys => {
    this.props.patchUserInfo(targetKeys);
  };
}

RoleAuthForm = Form.create()(RoleAuthForm);
